package com.itbaizhan.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author spf
 * @date 2024/4/26
 * @time 10:23
 */
@Component
@Slf4j
public class DistributeRedisLock {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 加锁
     *
     * @param lockName
     * @return
     * @throws InterruptedException
     */
    public Boolean lock(String lockName) throws InterruptedException {
        if (redissonClient == null) {
            return false;
        }
        try {
            RLock lock = redissonClient.getLock(lockName);
            lock.lock(10, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 释放锁
     * @param lockName
     * @return
     */
    public Boolean unlock(String lockName) {
        if (redissonClient == null) {
            return false;
        }

        try {
            RLock lock = redissonClient.getLock(lockName);
            lock.unlock();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
